/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.app.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.xw.app.imageupload.ImageUploadFactory;
import com.xw.app.imageupload.ImageUploadMethod;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

/**
 * The Class ImageUpload.
 *
 * @author Xi Wei
 */
@Component
public class ImageUpload {

	/** The log. */
	protected Logger log = LoggerFactory.getLogger(getClass());
	private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmssSSS";
	
	/** The image upload path. */
	@Value("${image_upload_path}")
	public String imageUploadPath;

	/** The image access url. */
	@Value("${image.access.url}")
	public String imageAccessUrl;

	/** The upload type. */
	@Value("${upload.type}")
	public String uploadType;

	/** The upload folder prefix. */
	@Value("${upload.folder.prefix}")
	public String uploadFolderPrefix;
	
	/**
	 * Check is empty.
	 *
	 * @param file the file
	 * @return true, if successful
	 */
	public boolean checkIsEmpty(MultipartFile file) {
		if (file.getSize() == 0) {
			return true;
		}
		return false;
	}

	/**
	 * Check is image.
	 *
	 * @param file the file
	 * @return true, if successful
	 */
	public boolean checkIsImage(MultipartFile file) {
		String uploadContentType = file.getContentType();

		if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
			return true;
		} else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
			// IE6上传的png图片的headimageContentType是"image/x-png"
			return true;
		} else if (uploadContentType.equals("image/gif")) {
			return true;
		} else if (uploadContentType.equals("image/bmp")) {
			return true;
		} else if(uploadContentType.equals("application/octet-stream")){
			return true;
		}else if(uploadContentType.equals("application/zip")){
			return true;
		}else {
			return false;
		}
	}

	/**
	 * Check thumbnail size.
	 *
	 * @param file the file
	 * @return the string
	 */
	public String checkThumbnailSize(MultipartFile file) {
		/*
		 * if(file.getSize() > 20 * 1024){ return "error.thumbnail.size"; }else{
		 * return ""; }
		 */
		return "";
	}

	/**
	 * Check detail image size.
	 *
	 * @param file the file
	 * @return the string
	 */
	public String checkDetailImageSize(MultipartFile file) {
		if (file.getSize() > 100 * 1024) {
			return "error.productpic.size";
		} else {
			return "";
		}
	}

	/**
	 * Upload image.
	 *
	 * @param request the request
	 * @param file the file
	 * @param relativePath the relative path
	 * @return the string
	 * @throws Exception the exception
	 */
	public String uploadImage(HttpServletRequest request, MultipartFile file, String relativePath) throws Exception {
		System.out.println("ImageUploadPath = " + imageUploadPath);

		if (uploadFolderPrefix == null) {
			uploadFolderPrefix = "";
		}
		if (file != null) {

			String expandedName = "";
			String uploadContentType = file.getContentType();
			if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
				expandedName = ".jpg";
			} else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
				// IE6上传的png图片的headimageContentType是"image/x-png"
				expandedName = ".png";
			} else if (uploadContentType.equals("image/gif")) {
				expandedName = ".gif";
			} else if (uploadContentType.equals("image/bmp")) {
				expandedName = ".bmp";
			}else if(uploadContentType.equals("application/octet-stream")){
				expandedName = ".rar";
			}else if(uploadContentType.equals("application/zip")){
				expandedName = ".zip";
			}

			DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
			String fileName = df.format(new Date()) + expandedName;

			log.info("The Session Context Path is " + request.getSession().getServletContext());
			log.info("The Context Path is " + request.getContextPath());
			log.info("The Configured upload path is " + imageUploadPath);

			String accessUrl = "";

			ImageUploadMethod uploadMethod = ImageUploadFactory.getInstance().getImageUploadMethod();
			accessUrl = uploadMethod.uploadImage(request, file, relativePath, fileName);

			return accessUrl;

		}
		return null;

	}

	/**
	 * Upload image.
	 *
	 * @param request the request
	 * @param file the file
	 * @param relativePath the relative path
	 * @param requiredWidth the required width
	 * @param requiredHeight the required height
	 * @return the string
	 * @throws Exception the exception
	 */
	public String uploadImage(HttpServletRequest request, MultipartFile file, String relativePath, int requiredWidth, int requiredHeight) throws Exception {
		System.out.println("ImageUploadPath = " + imageUploadPath);

		if (uploadFolderPrefix == null) {
			uploadFolderPrefix = "";
		}
		if (file != null) {

			String expandedName = "";
			String uploadContentType = file.getContentType();
			if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
				expandedName = ".jpg";
			} else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
				// IE6上传的png图片的headimageContentType是"image/x-png"
				expandedName = ".png";
			} else if (uploadContentType.equals("image/gif")) {
				expandedName = ".gif";
			} else if (uploadContentType.equals("image/bmp")) {
				expandedName = ".bmp";
			}

			DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
			String fileName = df.format(new Date()) + expandedName;

			BufferedImage sourceImg = ImageIO.read(file.getInputStream());

			// 首先对图片进行缩放
			int width = requiredWidth;
			int height = sourceImg.getHeight() * requiredWidth / sourceImg.getWidth();
			ByteArrayOutputStream bs = new ByteArrayOutputStream();

			Thumbnails.of(sourceImg).size(width, height).outputFormat(expandedName.substring(1)).toOutputStream(bs);
			InputStream is = new ByteArrayInputStream(bs.toByteArray());

			bs = new ByteArrayOutputStream();
			Thumbnails.of(is).sourceRegion(Positions.CENTER, requiredWidth, requiredHeight).size(requiredWidth, requiredHeight).outputFormat(expandedName.substring(1)).toOutputStream(bs);
			is = new ByteArrayInputStream(bs.toByteArray());
			return uploadImage(request, is, relativePath, expandedName);

		}
		return null;

	}

	/**
	 * Upload thumbnail.
	 *
	 * @param request the request
	 * @param file the file
	 * @param relativePath the relative path
	 * @return the string
	 * @throws Exception the exception
	 */
	public String uploadThumbnail(HttpServletRequest request, MultipartFile file, String relativePath) throws Exception {
		System.out.println("ImageUploadPath = " + imageUploadPath);

		if (uploadFolderPrefix == null) {
			uploadFolderPrefix = "";
		}
		if (file != null) {

			String expandedName = "";
			String uploadContentType = file.getContentType();
			if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
				expandedName = ".jpg";
			} else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
				// IE6上传的png图片的headimageContentType是"image/x-png"
				expandedName = ".png";
			} else if (uploadContentType.equals("image/gif")) {
				expandedName = ".gif";
			} else if (uploadContentType.equals("image/bmp")) {
				expandedName = ".bmp";
			}

			DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
			String fileName = df.format(new Date()) + expandedName;

			BufferedImage sourceImg = ImageIO.read(file.getInputStream());
			int originalWidth = sourceImg.getWidth();
			int originalHeight = sourceImg.getHeight();

			int width = originalWidth;
			int height = originalHeight;

			int cutsize = 0;
			if (originalWidth >= originalHeight) {
				height = 200;
				width = sourceImg.getWidth() * 200 / sourceImg.getHeight();
				cutsize = originalHeight;

			} else {
				width = 200;
				height = sourceImg.getHeight() * 200 / sourceImg.getWidth();
				cutsize = originalWidth;
			}

			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			Thumbnails.of(sourceImg).sourceRegion(Positions.CENTER, cutsize, cutsize).size(200, 200).outputFormat(expandedName.substring(1)).toOutputStream(bs);
			InputStream is = new ByteArrayInputStream(bs.toByteArray());

			return uploadImage(request, is, relativePath, expandedName);

		}
		return null;

	}

	/**
	 * Upload image.
	 *
	 * @param request the request
	 * @param is the is
	 * @param relativePath the relative path
	 * @param expandedName the expanded name
	 * @return the string
	 * @throws Exception the exception
	 */
	public String uploadImage(HttpServletRequest request, InputStream is, String relativePath, String expandedName) throws Exception {
		System.out.println("ImageUploadPath = " + imageUploadPath);

		if (uploadFolderPrefix == null) {
			uploadFolderPrefix = "";
		}
		if (is != null) {

			DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
			String fileName = "";
			if (expandedName.startsWith(".")) {
				fileName = df.format(new Date()) + expandedName;
			} else {
				fileName = df.format(new Date()) + "." + expandedName;
			}

			log.info("The Session Context Path is " + request.getSession().getServletContext());
			log.info("The Context Path is " + request.getContextPath());
			log.info("The Configured upload path is " + imageUploadPath);

			String path = "";
			String accessUrl = "";

			ImageUploadMethod uploadMethod = ImageUploadFactory.getInstance().getImageUploadMethod();
			accessUrl = uploadMethod.uploadImage(request, is, relativePath, fileName);

			return accessUrl;

		}
		return null;

	}
}
